<template>
  <el-dialog
    title="分配权限"
    :visible="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    center
  >
    <el-tree
      ref="tree"
      v-loading="isLoading > 0"
      :data="auth_list"
      show-checkbox
      default-expand-all
      node-key="id"
      :check-strictly="true"
      highlight-current
      :props=" {
        children: 'children',
        label: 'auth_name'
      }"
    />
    <div class="btn-box">
      <el-button type="primary" size="mini" @click="submitForm()">提交</el-button>
      <el-button size="mini" @click="resetForm()">重置</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { getAuthListAll } from '@/api/auth'
import { transListToTreeData } from '@/utils/tools'
import { updateOneRoleById } from '@/api/role'
export default {
  name: 'RoleAddEdit',
  components: {},
  props: {},
  data() {
    return {
      dialogVisible: false,
      isLoading: 0,
      auth_list: [],
      role_id: '',
      checked_arr_origin: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getAuthListAll()
  },
  mounted() {},
  methods: {
    async getAuthListAll() {
      this.isLoading++
      try {
        let res = await getAuthListAll()
        res = res.filter(item => item.status === 1)
        this.auth_list = transListToTreeData(res)
      } finally {
        this.isLoading--
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    open(row) {
      this.dialogVisible = true
      this.role_id = row.id
      this.checked_arr_origin = JSON.parse(row.auth_list_json)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.checked_arr_origin)
      })
    },
    resetForm() {
      this.$refs.tree.setCheckedKeys(this.checked_arr_origin)
    },
    async submitForm() {
      if (this.isLoading > 0) return
      try {
        this.isLoading++
        const checked_arr = this.$refs.tree.getCheckedKeys()
        await updateOneRoleById({
          id: this.role_id,
          auth_list_json: JSON.stringify(checked_arr)
        })
        this.$emit('refresh')
        this.handleClose()
      } finally {
        this.isLoading--
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.submit-box {
  display: flex;
  justify-content: flex-end;
}
.btn-box {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
